'use strict';

angular.module('myapp')
    .factory('Content', ['$resource', function ($resource) {

        return $resource('/api/contents/:id', {
            id: '@_id'
        }, {
            'update': {
                method: 'PUT'
            }
        });

}]);


var appId = '04251B9B';
var messageNS = 'urn:x-cast:com.google.cast.sample.helloworld';


angular.module('myapp')
    .controller('playlistCtrl', ['$scope', 'Content', 'ChromeCastSenderChannel', '$mdSidenav', '$mdToast', function ($scope, Content, ChromeCastSenderChannel, $mdSidenav, $mdToast) {

        $scope.contents = Content.query();
        $scope.sideNav = true;
        $scope.casting = false;

        $scope.add = function () {

            var content = new Content();
            content.name = 'image1.png1';
            content.enable = true;
            content.duration = 10;
            content.$save();

            $scope.contents = Content.query();
        }

        $scope.remove = function (content) {

            content.$delete();

            $scope.contents = Content.query();
        }

        $scope.casting = ChromeCastSenderChannel.isStarted();

        $scope.onPlay = function () {

            if(ChromeCastSenderChannel.isStarted()) {

                ChromeCastSenderChannel.stopSession(function() {
                    $scope.casting = false;
                    $scope.$apply();

                    $mdToast.show($mdToast.simple().content('Casting stopped'));
                });

            } else {

                ChromeCastSenderChannel.startSession(function() {
                    $scope.casting = true;
                    $scope.$apply();

                    $mdToast.show($mdToast.simple().content('Casting started'));

                }, function(e) {

                   $mdToast.show($mdToast.simple().content('Session error: ' + e.code));
                });
            }
        }

        $scope.onMenu = function() {
            $mdSidenav('left').toggle();
        }

}]);


angular.module('myapp')
    .controller('contentCtrl', ['$scope', 'Content', 'FileUploader', function ($scope, Content, FileUploader) {

        $scope.$watch('content', function (newVal, oldVal) {

            Content.update({
                id: newVal._id
            }, newVal);

        }, true);

        $scope.uploader = new FileUploader({
            url: '/api/contents/' + $scope.content._id + '/media',
            autoUpload: true,
            removeAfterUpload: true
        });

        $scope.isFlash = $scope.content.name.indexOf('.swf') != -1;

        $scope.uploader.onCompleteAll = function () {

            var entry = Content.get({
                id: $scope.content._id
            }, function () {
                $scope.content = entry;
                $scope.isFlash = content.name.indexOf('.swf') != -1;
            });
        }

}]);
